import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:tencent_cloud_chat_uikit/czm_custom_widget/czm_widget_bridge.dart';
import 'package:tencent_cloud_chat_uikit/czm_method/czm_method_bridge.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/common_utils.dart';
import 'package:tencent_im_base/tencent_im_base.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_state.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_friendship_view_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';

import 'package:tencent_cloud_chat_uikit/ui/widgets/avatar.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/az_list_view.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/radio_button.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_base.dart';

class ContactList extends StatefulWidget {
  final List<V2TimFriendInfo> contactList;
  final bool isCanSelectMemberItem;
  final bool isCanSlidableDelete;
  final Function(List<V2TimFriendInfo> selectedMember)? onSelectedMemberItemChange;
  final Function()? handleSlidableDelte;

  /// tap联系人列表项回调
  final void Function(V2TimFriendInfo item)? onTapItem;

  /// 顶部列表
  final List<TopListItem>? topList;

  /// 顶部列表项构造器
  final Widget? Function(TopListItem item)? topListItemBuilder;

  /// Control if shows the online status for each user on its avatar.
  final bool isShowOnlineStatus;

  final int? maxSelectNum;

  final List<V2TimGroupMemberFullInfo?>? groupMemberList;

  /// the builder for the empty item, especially when there is no contact
  final Widget Function(BuildContext context)? emptyBuilder;

  const ContactList(
      {Key? key,
      required this.contactList,
      this.isCanSelectMemberItem = false,
      this.onSelectedMemberItemChange,
      this.isCanSlidableDelete = false,
      this.handleSlidableDelte,
      this.onTapItem,
      this.topList,
      this.topListItemBuilder,
      this.isShowOnlineStatus = false,
      this.maxSelectNum,
      this.groupMemberList,
      this.emptyBuilder})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _ContactListState();
}

class _ContactListState extends TIMUIKitState<ContactList> {
  List<V2TimFriendInfo> selectedMember = [];
  final TUIFriendShipViewModel friendShipViewModel = serviceLocator<TUIFriendShipViewModel>();

  @override
  initState() {
    CZMMethodBridge.getInstance().contactInitStateCallBack(widget.contactList);
    super.initState();
  }

  _getShowName(V2TimFriendInfo item) {
    final friendRemark = item.friendRemark ?? "";
    final nickName = item.userProfile?.nickName ?? "";
    return friendRemark != "" ? friendRemark : nickName;
  }

  List<ISuspensionBeanImpl> _getShowList(List<V2TimFriendInfo> memberList) {
    final List<ISuspensionBeanImpl> showList = List.empty(growable: true);
    for (var i = 0; i < memberList.length; i++) {
      final item = memberList[i];
      final showName = _getShowName(item);
      String pinyin = PinyinHelper.getPinyinE(showName);
      String tag = pinyin.substring(0, 1).toUpperCase();
      if (RegExp("[A-Z]").hasMatch(tag)) {
        showList.add(ISuspensionBeanImpl(memberInfo: item, tagIndex: tag));
      } else {
        showList.add(ISuspensionBeanImpl(memberInfo: item, tagIndex: "#"));
      }
    }

    SuspensionUtil.sortListBySuspensionTag(showList);

    return showList;
  }

  bool selectedMemberIsOverFlow() {
    if (widget.maxSelectNum == null) {
      return false;
    }

    return selectedMember.length >= widget.maxSelectNum!;
  }

  Widget _buildItem(TUITheme theme, V2TimFriendInfo item) {
    final showName = _getShowName(item);
    final faceUrl = item.userProfile?.faceUrl ?? "";

    final V2TimUserStatus? onlineStatus = widget.isShowOnlineStatus
        ? friendShipViewModel.userStatusList
            .firstWhere((element) => element.userID == item.userID, orElse: () => V2TimUserStatus(statusType: 0))
        : null;

    bool disabled = false;
    if (widget.groupMemberList != null && widget.groupMemberList!.isNotEmpty) {
      disabled = ((widget.groupMemberList?.indexWhere((element) => element?.userID == item.userID)) ?? -1) > -1;
    }
    return Container(
      height: 65,
      padding: const EdgeInsets.symmetric(horizontal: 17),
      child: Row(
        children: [
          if (widget.isCanSelectMemberItem) // 是否有选中框
            Container(
              margin: const EdgeInsets.only(right: 12, bottom: 8),
              child: CheckBoxButton(
                disabled: disabled,
                isChecked: selectedMember.contains(item),
                onChanged: (isChecked) {
                  if (isChecked) {
                    if (selectedMemberIsOverFlow()) {
                      return;
                    }
                    selectedMember.add(item);
                  } else {
                    selectedMember.remove(item);
                  }
                  if (widget.onSelectedMemberItemChange != null) {
                    widget.onSelectedMemberItemChange!(selectedMember);
                  }
                  setState(() {});
                },
              ),
            ),
          SizedBox(
            height: 45,
            width: 45,
            child: Avatar(onlineStatus: onlineStatus, faceUrl: faceUrl, showName: showName),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 8),
            child: ConstrainedBox(
              constraints: BoxConstraints(maxWidth: (MediaQuery.of(context).size.width) * .58),
              child: Text(
                showName,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  color: Color(0xFF1D2541),
                  fontSize: 15,
                  fontWeight: FontWeight.normal,
                ),
              ),
            ),
          ),
          CZMWidgetBuilderBridge.getInstance().userTag(context, item.userID),
        ],
      ),
    );
  }

  Widget generateTopItem(memberInfo) {
    if (widget.topListItemBuilder != null) {
      final customWidget = widget.topListItemBuilder!(memberInfo);
      if (customWidget != null) {
        return customWidget;
      }
    }
    return InkWell(
        onTap: () => (memberInfo.onTap != null) ? memberInfo.onTap!() : null,
        child: SizedBox(
          height: 62,
          child: Row(
            children: [
              SizedBox(height: 36, width: 36, child: memberInfo.icon),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  memberInfo.name,
                  style: TextStyle(color: hexToColor("111111"), fontSize: 18),
                ),
              ),
              Image.asset('images/ic_arrow_right.webp', package: 'tencent_cloud_chat_uikit', width: 13, height: 13),
            ],
          ),
        ));
  }

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    final TUITheme theme = value.theme;

    final showList = _getShowList(widget.contactList);
    Widget? topListWidget;
    if (widget.topList != null && widget.topList!.isNotEmpty) {
      final list = widget.topList!.map((e) => generateTopItem(e)).toList();
      final topLists = TencentUtils.joined(list, () => const Divider(thickness: 0.5, color: Color(0xFFEEEFF3)));
      topListWidget = Container(
        width: double.infinity,
        margin: const EdgeInsets.symmetric(horizontal: 17).copyWith(bottom: 10, top: 8),
        padding: const EdgeInsets.symmetric(horizontal: 17),
        decoration: BoxDecoration(color: Colors.white60, borderRadius: BorderRadius.circular(12)),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 5),
            ...topLists,
            const SizedBox(height: 5),
          ],
        ),
      );
    }

    if (widget.contactList.isEmpty) {
      return Column(
        children: [
          if (topListWidget != null) topListWidget,
          Expanded(child: widget.emptyBuilder != null ? widget.emptyBuilder!(context) : const SizedBox.shrink())
        ],
      );
    }
    ISuspensionBeanImpl showTopListBean;
    if (topListWidget != null) {
      showTopListBean = ISuspensionBeanImpl(memberInfo: topListWidget, tagIndex: '@');
      showList.insert(0, showTopListBean);
    }

    return AZListViewContainer(
      memberList: showList,
      itemBuilder: (context, index) {
        final memberInfo = showList[index].memberInfo;
        if (memberInfo is Widget) {
          return memberInfo;
        } else {
          return InkWell(
            onTap: () {
              if (widget.isCanSelectMemberItem) {
                if (selectedMember.contains(memberInfo)) {
                  selectedMember.remove(memberInfo);
                } else {
                  if (selectedMemberIsOverFlow()) {
                    return;
                  }
                  selectedMember.add(memberInfo);
                }
                if (widget.onSelectedMemberItemChange != null) {
                  widget.onSelectedMemberItemChange!(selectedMember);
                }
                setState(() {});
                return;
              }
              if (widget.onTapItem != null) {
                widget.onTapItem!(memberInfo);
              }
            },
            child: _buildItem(theme, memberInfo),
          );
        }
      },
    );
  }
}

class TopListItem {
  final String name;
  final String id;
  final Widget? icon;
  final Function()? onTap;

  TopListItem({required this.name, required this.id, this.icon, this.onTap});
}
